// 全局变量
var currentPage = 1;

// 加载文件列表
function loadFileList() {
    console.log('开始加载文件列表');

    $('#fileTableBody').html('<tr><td colspan="5" style="text-align: center;">加载中...</td></tr>');

    var params = {
        prefix: $('#prefixInput').val(),
        bucket: $('#bucketSelect').val(),
        marker: ''
    };

    $.ajax({
        url: '/renren-admin/pms/qiniu/list',
        type: 'GET',
        data: params,
        success: function(response) {
            console.log('文件列表响应:', response);
            if (response.code === 0) {
                renderFileList(response.data);
            } else {
                alert('加载失败：' + response.msg);
                $('#fileTableBody').html('<tr><td colspan="5" style="text-align: center;">加载失败</td></tr>');
            }
        },
        error: function(xhr, status, error) {
            console.error('加载文件列表错误:', error);
            alert('网络错误，请稍后重试');
            $('#fileTableBody').html('<tr><td colspan="5" style="text-align: center;">网络错误</td></tr>');
        }
    });
}

// 渲染文件列表
function renderFileList(data) {
    console.log('渲染文件列表:', data);
    var tbody = $('#fileTableBody');
    tbody.empty();

    if (!data || !data.items || data.items.length === 0) {
        tbody.html('<tr><td colspan="5" style="text-align: center;">暂无文件</td></tr>');
        return;
    }

    data.items.forEach(function(file) {
        var row = '<tr>' +
            '<td>' +
            '<div class="file-name">' +
            '<i class="fa fa-file-o file-icon"></i>' +
            '<span title="' + file.key + '">' + file.key + '</span>' +
            '</div>' +
            '</td>' +
            '<td>' + formatFileSize(file.size) + '</td>' +
            '<td>' + (file.mimeType || '未知') + '</td>' +
            '<td>' + formatTime(file.putTime) + '</td>' +
            '<td>' +
            '<button type="button" class="btn btn-xs btn-success" onclick="downloadFile(\'' + file.url + '\', \'' + file.key + '\')">下载</button> ' +
            '<button type="button" class="btn btn-xs btn-danger" onclick="deleteFile(\'' + file.key + '\')">删除</button>' +
            '</td>' +
            '</tr>';
        tbody.append(row);
    });
}

// 执行上传
function doUpload() {
    console.log('开始上传文件');

    var fileInput = $('#fileInput')[0];
    if (!fileInput.files || fileInput.files.length === 0) {
        alert('请选择要上传的文件');
        return;
    }

    var formData = new FormData();
    formData.append('file', fileInput.files[0]);
    formData.append('bucket', $('#uploadBucket').val());

    $('#uploadProgress').show();

    $.ajax({
        url: '/renren-admin/pms/qiniu/upload',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        xhr: function() {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = (evt.loaded / evt.total) * 100;
                    $('.progress-bar').css('width', percentComplete + '%').text(percentComplete.toFixed(1) + '%');
                }
            }, false);
            return xhr;
        },
        success: function(response) {
            console.log('上传响应:', response);
            if (response.code === 0) {
                alert('上传成功');
                $('#uploadModal').modal('hide');
                loadFileList();
            } else {
                alert('上传失败：' + response.msg);
            }
        },
        error: function(xhr, status, error) {
            console.error('上传错误:', error);
            alert('上传失败，请检查网络连接');
        },
        complete: function() {
            $('#uploadProgress').hide();
        }
    });
}

// 删除文件
function deleteFile(fileName) {
    if (!confirm('确定要删除文件 "' + fileName + '" 吗？')) {
        return;
    }

    var params = {
        fileName: fileName,
        bucket: $('#bucketSelect').val()
    };

    $.ajax({
        url: '/renren-admin/pms/qiniu/delete',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(params),
        success: function(response) {
            console.log('删除响应:', response);
            if (response.code === 0) {
                alert('删除成功');
                loadFileList();
            } else {
                alert('删除失败：' + response.msg);
            }
        },
        error: function(xhr, status, error) {
            console.error('删除错误:', error);
            alert('删除失败，请稍后重试');
        }
    });
}

// 下载文件
function downloadFile(url, fileName) {
    window.open(url);
}

// 工具函数
function formatFileSize(bytes) {
    if (!bytes) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB'];
    let size = bytes;
    let unitIndex = 0;
    while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
    }
    return size.toFixed(1) + ' ' + units[unitIndex];
}

function formatTime(timestamp) {
    if (!timestamp) return '-';
    var date = new Date(timestamp / 10000);
    return date.toLocaleString();
}